<?php 
/**
 * Created by Sublime
 * User: yinni
 * Date: 2017/11/29 14:08
 */
namespace App\Services\Admin;

use Facades\App\Repositories\Eloquent\CoringRepository;
use Facades\App\Repositories\Eloquent\UserRepository;
use Facades\App\Repositories\Eloquent\RoleRepository;
use Facades\App\Repositories\Eloquent\RiversRepository;
use Facades\App\Repositories\Eloquent\Rivers_alarmRepository;
use Facades\App\Repositories\Eloquent\Rivers_alarm_historyRepository;
use Facades\App\Repositories\Eloquent\Town_riverRepository;
use Facades\App\Repositories\Eloquent\County_townRepository;
use Facades\App\Repositories\Eloquent\City_countyRepository;

use Facades\Yajra\DataTables\Html\Builder;

use App\Repositories\Traits\DatatableActionButtonTrait;
use Datatables;
use Exception;
use DB;

class CoringService{
	use DatatableActionButtonTrait;

	protected $module = 'coring'; //模块路由

	protected $indexRoute = 'coring.index'; 

	protected $createRoute = 'coring.create';

	protected $showRoute = 'coring.show';

	protected $editRoute = 'coring.edit';

	protected $destroyRoute = 'coring.destroy';

    // 微信模板消息推送
    protected $appid = 'wx9ad63a20b597ff1f';
    protected $appsecret = 'e37c09ce7f122137bc2066fed909d732';
    protected $access_token = '6YkeUJ9HkhK7z6zHZuuX-VWLwSqQf-Du8Ovom8aK1SxHfhmmixhUsHIG0FA4nNJ3pEVYvQDRDbc4HbhU71LMVeQNjzobcSJchh0f3O28wDcGlM7IZv5ITAP57gtlAyJ9VUKgAHAMLB';
    protected $lasttime = 1406469747;

    public function __construct() {
        // 定义当前需使用的数据表
        $this->coring = CoringRepository::all();
        $this->user = UserRepository::all();
        $this->role = RoleRepository::all();
        $this->rivers = RiversRepository::all();
        // $this->town_river = Town_riverRepository::all();
        $this->county_town = County_townRepository::all();
        $this->county_town = City_countyRepository::all();
        $this->rivers_alarm = rivers_alarmRepository::all();
        $this->rivers_alarm_history = rivers_alarm_historyRepository::all();
    }


	/**
	 * 首页
	 * @return array
	 */
	public function index() {
		if(request()->ajax()) {
			return $this->ajaxData();
		}
        $html = Builder::parameters([
            'searchDelay' => 350,
            'language' => [
                'url' => url(getThemeAssets('dataTables/language/zh.json', true))
            ],
            'drawCallback' => <<<Eof
					function() {
				        LaravelDataTables["dataTableBuilder"].$('.tooltips').tooltip( {
				          placement : 'top',
				          html : true
				        });
			        },
Eof
        ])->addIndex(['data' => 'DT_Row_Index', 'name' => 'DT_Row_Index', 'title' => trans('common.number')])
            ->addColumn(['data' => 'core_id', 'name' => 'core_id', 'title' => trans('coring.core_id')])
            ->addColumn(['data' => 'loop_name', 'name' => 'loop_name', 'title' => trans('coring.loop_name')])
            ->addColumn(['data' => 'resi_current', 'name' => 'resi_current', 'title' => trans('coring.resi_current')])
            ->addColumn(['data' => 'cable_temp', 'name' => 'cable_temp', 'title' => trans('coring.cable_temp')])
            ->addColumn(['data' => 'location', 'name' => 'location', 'title' => trans('coring.location')])
            ->addColumn(['data' => 'smoke', 'name' => 'smoke', 'title' => trans('coring.smoke')])
            ->addColumn(['data' => 'fire', 'name' => 'fire', 'title' => trans('coring.fire')])
            ->addAction(['data' => 'near_infrared', 'name' => 'near_infrared', 'title' => trans('coring.near_infrared')]);

            return compact('html');
        }

    /**
     * datatable数据,核心逻辑处理
     * @return mixed
     */
    public function ajaxData() {
        // 取出core表的所有信息
        $alltimeinfo_data = DB::table('core')->get();
        $alltimeinfo_data = json_decode($alltimeinfo_data,true);
        foreach ($alltimeinfo_data as $key => $value) {
            // 根据river_id进行取出每条河道的id
            $temp_river_id = $alltimeinfo_data[$key]['river_id'];

            // 取出实时监测数据
            $temp_temp = $alltimeinfo_data[$key]['temp'];
            $temp_height = $alltimeinfo_data[$key]['height'];
            $temp_ph = $alltimeinfo_data[$key]['ph'];
            $temp_turbidity = $alltimeinfo_data[$key]['turbidity'];

            // 根据当前的river_id，从town_river中取出关联信息,乡镇编号、名称、负责人信息
            $temp_town_info = DB::table('town_river')->where('river_id',$temp_river_id)->first();
            $temp_town_name = $temp_town_info->town_name;
            $temp_town_manager_id = $temp_town_info->town_manager_id;
	    $temp_town_manager_name = DB::table('users')->where('id',$temp_town_manager_id)->value('name');
            $temp_town_manager_email = $temp_town_info->town_manager_email;
            $temp_town_manager_openid = $temp_town_info->town_manager_openid;
            
            // 将部分信息添加至ajax数组中
            $alltimeinfo_data[$key]['town_name'] = $temp_town_name;
	    $alltimeinfo_data[$key]['manager_name'] = $temp_town_manager_name;
	    $alltimeinfo_data[$key]['email'] = $temp_town_manager_email;

            // 从rivers定义表取出所有的河道id
            $rivers_all = $this->rivers->pluck('river_id')->toArray();

            // 预判当前河道id是否在全部河流中
            if (in_array($temp_river_id, $rivers_all)) {
                // 针对当前的河道id取出定义表中的额定值
                $temp_river_std = $this->rivers->where('river_id',$temp_river_id)->first()->toArray();
                $temp_temp_std = $temp_river_std['temp_std'];
                $temp_height_std = $temp_river_std['height_std'];
                $temp_ph_std = $temp_river_std['ph_std'];
                $temp_turbidity_std = $temp_river_std['turbidity_std'];

                // 保存部分结果值ajax数组中
                $alltimeinfo_data[$key]['river_name'] = $temp_river_std['river_name'];
                $alltimeinfo_data[$key]['nl'] = $temp_river_std['nl'];
                $alltimeinfo_data[$key]['el'] = $temp_river_std['el'];

                // 保存判断结果并返回报警状态至ajax前端
                $result['temp'] = 0;
                $result['height'] = 0;
                $result['ph'] = 0;
                $result['turbidity'] = 0;
                $alarm_status = 0;
                if ($temp_height_std < $temp_height) {
                    $result['height'] = 1;
                    $alarm_status = 1;
                }
                if ($temp_turbidity_std < $temp_turbidity) {
                    $result['turbidity'] = 1;
                    $alarm_status = 1;
                }
                if ($temp_ph_std > $temp_ph ) {
                    $result['ph'] = 1;
                    $alarm_status = 1;
                }
                // 将其添加至Ajax数组中
                $alltimeinfo_data[$key]['height'] = $result['height'];
                $alltimeinfo_data[$key]['ph'] = $result['ph'];
                $alltimeinfo_data[$key]['turbidity'] = $result['turbidity'];
                if ($alarm_status == 1) {
                    $alltimeinfo_data[$key]['status'] = 2;
                }

                // 将已发生报警的回路信息更新至river_alarm表中，处理完成后添加至river_alarm_history表中
                if ($alarm_status == 1) {
                    // 取出当前river在monitor_alarm表中的最新记录，比较三个值的报警状状态
                    $river_alarm_data['start_time'] = date('Y-m-d H:i:s',time());
                    $river_alarm_data['alarm_send'] = 0;
                    if ($result['height'] ==1) {
                        $river_alarm_data['height'] = 1;
                    }
                    if ($result['ph'] ==1) {
                        $river_alarm_data['ph'] = 1;
                    }
                    if ($result['turbidity'] ==1) {
                        $river_alarm_data['turbidity'] = 1;
                    }

                    // 在已发生报警的前提下对比river_alarm表进行邮件、微信信息发送,river_alarm_history记录插入
                    // 取出river_alarm数据
                    $temp_waiting_record = $this->rivers_alarm->where('river_id',$temp_river_id)->first()->toArray();
                    $record['height'] = $temp_waiting_record['height'];
                    $record['ph'] = $temp_waiting_record['ph'];
                    $record['turbidity'] = $temp_waiting_record['turbidity'];
                    $record['alarm_send'] = $temp_waiting_record['alarm_send'];

                    // 当任一记录值不一样时进行更新并发送报警信息
                    if (($record['height'] != $result['height']) || ($record['ph'] != $result['ph']) || ($record['turbidity'] != $result['turbidity'])) {
                        
                        // 更新rivers_alarm表
                        $res_update_data = DB::table('rivers_alarm')->where('river_id',$temp_river_id)->update(['start_time' => $river_alarm_data['start_time'],'status' => 0,'alarm_send' => 1,'height' => $result['height'],'ph' => $result['ph'],'turbidity' => $result['turbidity']]);
                        // dump($res_update_data);die;
                    }else {

                    }

                }else {

                }
                // dump($temp_turbidity_std);die;
            }
        }
        
        
        return $alltimeinfo_data;
   //  	return Datatables::of(CoringRepositoryEloquent::all())
			// ->addIndexColumn()
			// ->addColumn('action', function ($permission)
			// {
			// 	return $this->getActionButtonAttribute($permission->id);
			// })
			// ->make(true);
    }

    /**
     * 实时监测json数据
     * @return json
     */
    public function ajaxJsonData() {
        return CoringRepositoryEloquent::all();
    }

    /**
     * 重写datatable action按钮
     * @param $id
     * @return string
     */
    public function getActionButtonAttribute($id)
    {
        return $this->getShowActionButtion($id).
            $this->getEditActionButton($id).
            $this->getDestroyActionButton($id);
    }

    /**
     * 跟据当前用户取出所管辖的河道,主要分superadmin、user、townmanager
     * @param $username string
     * @return array json
     */
    public function getManagerRivers($username = null) {
        $username = auth()->user()->username;
        // 关联role_user取出role_id
        $user_id = $this->user->where('username',$username)->pluck('id');
        $role_id = DB::table('role_user')->where('user_id',$user_id)->value('role_id');
        // 取出slug分类
        $role_slug = $this->role->where('id',$role_id)->pluck('slug');
        // 管理员取出所有信息
        if ($role_slug[0] == 'admin') {
            // 系统最高级为苏州市，slug == admin 
            $rivers_all['city'] = DB::table('city_county')->distinct()->pluck('city_name'); 
            // 取出所有县（区）,三张关键表均为多对多关系，降级查找进行去重
            $rivers_all['county'] = DB::table('county_town')->distinct()->pluck('county_name');
            $rivers_all['town'] = DB::table('town_river')->distinct()->pluck('town_name');
            // $rivers_all['info'] = $this->rivers->toArray();
            $rivers_all['amount'] = $this->rivers->count();
        }else if ($role_slug[0] == 'townmanager') {
            // 取出当前用户对应所掌管的河流
            // $rivers_all['info'] = $this->town_river->where('town_manager_id',$user_id)->get();
            $rivers_all['amount'] = $this->town_river->where('town_manager_id',$user_id)->count();
        }else if ($role_slug[0] == 'countymanager') {

        }else {
            
        }
        // dump(response()->json($rivers_all));die;
        return response()->json($rivers_all);
    }

    /**
     * 查看
     * @param $id
     * @return array|\Illuminate\Http\RedirectResponse
     */
    public function show($id)
    {
        // try {
        //     $user = UserRepositoryEloquent::with(['userPermissions', 'roles'])->find(decodeId($id, $this->module));
        //     $permissions = $this->getAllPermissions();
        //     $roles = $this->getAllRole();
        //     return compact('user', 'permissions', 'roles');
        // } catch (Exception $e) {
        //     flash(trans('common.find_error'), 'danger');
        //     return redirect()->route($this->indexRoute);
        // }
    }

    // 发送模板消息
    public function send_tpl_msg($data) {
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->access_token;
        $res = $this->http_request($url,$data);
        return $res;
    }

    // 向微信客户端发起http POST请求
    // 包含access_token以及模板消息的发送
    public function http_request($url, $data = null) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // 发送模板消息
        if (!empty($data)) {
            curl_setopt($ch,CURLOPT_POST,1);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
        }
        // token值的获取
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $out = curl_exec($ch);
        curl_close($ch);
        return  json_decode($out,true);     
    }


}
